package com.zzqstart.msgservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;

import com.zzqstart.commonutils.RandomUtil;
import com.zzqstart.msgservice.service.MsgService;
import com.zzqstart.msgservice.utils.ConstantPropertiesUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: MsgServiceImpl
 * Package: com.atguigu.Msgservice.service.impl
 * Description:
 *
 * @Author zzqstart
 * @Create 2023-02-28 23:31
 * @Version 1.0
 */
@Service
public class MsgServiceImpl implements MsgService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean send(String phone) {
        if (StringUtils.isEmpty(phone)) return false;

        // 生成验证码
        String code = RandomUtil.getFourBitRandom();
        HashMap<String, Object> param = new HashMap<>();
        param.put("code", code);

        try {
            // 初始化client
            com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                    // 必填，您的 AccessKey ID
                    .setAccessKeyId(ConstantPropertiesUtils.KEY_ID)
                    // 必填，您的 AccessKey Secret
                    .setAccessKeySecret(ConstantPropertiesUtils.KEY_SECRET);
            // 访问的域名
            config.endpoint = "dysmsapi.aliyuncs.com";
            com.aliyun.dysmsapi20170525.Client client = new com.aliyun.dysmsapi20170525.Client(config);

            com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                    .setSignName("我的毕设学习之教育网站")
//                .setTemplateCode("SMS_154950909")
                    .setTemplateCode("SMS_271475665")
                    .setPhoneNumbers(phone)
                    .setTemplateParam(JSONObject.toJSONString(param));
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            // 发送成功后将数据保存在redis中，时长5min

            if (sendSmsResponse.statusCode == 200) {
                redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


}
